package com.lx.chong.utils;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.DateUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Excel操作工具类
 *
 * @author: chong
 * @date: 2018/5/14
 */
public class ExcelUtil {
    public String filePath;
    public String sheetName;
    public Workbook workBook;
    public Sheet sheet;
    public List<String> columnHeaderList;
    public List<List<String>> listData;
    public List<Map<String, String>> mapData;
    public boolean flag;


    public ExcelUtil(String filePath, String sheetName) {
        this.filePath = filePath;
        this.sheetName = sheetName;
        this.flag = false;
        this.load();
    }

    public ExcelUtil(String filePath, String sheetName, Boolean isUrlPath) {
        this.filePath = filePath;
        this.sheetName = sheetName;
        this.flag = false;
        this.load(isUrlPath);
    }

    private void load(boolean... isUrlPath) {
        FileInputStream inStream = null;
        try {
            if (isUrlPath != null && isUrlPath.length > 0) {
                HttpURLConnection httpConn;
                URL url = new URL(filePath);
                httpConn = (HttpURLConnection) url.openConnection();
                InputStream inputStream = httpConn.getInputStream();
                workBook = WorkbookFactory.create(inputStream);
                sheet = workBook.getSheet(sheetName);
            } else {
                inStream = new FileInputStream(new File(filePath));
                workBook = WorkbookFactory.create(inStream);
                sheet = workBook.getSheet(sheetName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inStream != null) {
                    inStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    private String getCellValue(Cell cell) {
        String cellValue = "";
        DataFormatter formatter = new DataFormatter();
        if (cell != null) {
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC:
                    if (DateUtil.isCellDateFormatted(cell)) {
                        cellValue = formatter.formatCellValue(cell);
                    } else {
                        double value = cell.getNumericCellValue();
                        int intValue = (int) value;
                        cellValue = value - intValue == 0 ? String.valueOf(intValue) : String.valueOf(value);
                    }
                    break;
                case Cell.CELL_TYPE_STRING:
                    cellValue = cell.getStringCellValue();
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    cellValue = String.valueOf(cell.getBooleanCellValue());
                    break;
                case Cell.CELL_TYPE_FORMULA:
                    cellValue = String.valueOf(cell.getCellFormula());
                    break;
                case Cell.CELL_TYPE_BLANK:
                    cellValue = "";
                    break;
                case Cell.CELL_TYPE_ERROR:
                    cellValue = "";
                    break;
                default:
                    cellValue = cell.toString().trim();
                    break;
            }
        }
        return cellValue.trim();
    }


    private void getSheetData() {
        listData = new ArrayList<>();
        mapData = new ArrayList<>();
        columnHeaderList = new ArrayList<>();
        int numOfRows = sheet.getLastRowNum() + 1;
        for (int i = 0; i < numOfRows; i++) {
            Row row = sheet.getRow(i);
            Map<String, String> map = new HashMap<>();
            List<String> list = new ArrayList<>();
            if (row != null) {
                int numOfCell = 0;
                if (i == 0) {
                    numOfCell = row.getLastCellNum();
                } else {
                    numOfCell = columnHeaderList.size();
                }
                for (int j = 0; j < numOfCell; j++) {
                    Cell cell = row.getCell(j);
                    if (i == 0) {
                        columnHeaderList.add(getCellValue(cell));
                    } else {
                        map.put(columnHeaderList.get(j), this.getCellValue(cell));
                    }
                    list.add(this.getCellValue(cell));
                }
            }
            if (i > 0) {
                mapData.add(map);
            }
            listData.add(list);
        }
        flag = true;
    }


    public String getCellData(int row, int col) {
        if (row <= 0 || col <= 0) {
            return null;
        }
        if (!flag) {
            this.getSheetData();
        }
        if (listData.size() >= row && listData.get(row - 1).size() >= col) {
            return listData.get(row - 1).get(col - 1);
        } else {
            return null;
        }
    }


    public String getCellData(int row, String headerName) {
        if (row <= 0) {
            return null;
        }
        if (!flag) {
            this.getSheetData();
        }
        if (mapData.size() >= row && mapData.get(row - 1).containsKey(headerName)) {
            return mapData.get(row - 1).get(headerName);
        } else {
            return null;
        }
    }


    /**
     * 获取标题
     *
     * @param eh
     * @param maxX
     * @return
     */
    public List<String> getTitleList(ExcelUtil eh, int maxX) {
        List<String> result = new ArrayList<>();
        for (int i = 1; i <= maxX; i++) {
            result.add(eh.getCellData(1, i));
        }
        return result;
    }

    /**
     * 获取导入支出项目标题
     *
     * @param eh
     * @param maxX
     * @return
     */
    public List<String> getProTitleList(ExcelUtil eh, int maxX) {
        List<String> result = new ArrayList<>();
        for (int i = 1; i <= maxX; i++) {
            int row = 3;
            if (i == 7 || i == 8 || i == 14 || i == 15) {
                row = 4;
            }
            result.add(eh.getCellData(row, i));
        }
        return result;
    }

    /**
     * 获取总行数
     *
     * @return
     */
    public int getRowNum() {
        return sheet.getLastRowNum();
    }

    /**
     * 获取总列数
     *
     * @return
     */
    public int getColNum() {
        Row row = sheet.getRow(0);
        return row.getLastCellNum();
    }


    /**
     * 获取单行对象
     *
     * @param className
     * @param eh
     * @param y
     * @param titles
     * @return
     */
    public Object getObject(String className, ExcelUtil eh, int y, List<String> titles) throws Exception {
        Object bean = Class.forName(className).newInstance();
        int length = titles.size();
        for (int x = 0; x < length; x++) {
            try {
                Field field = bean.getClass().getDeclaredField(titles.get(x));
                field.setAccessible(true);
                field.set(bean, eh.getCellData(y, x + 1));
            } catch (Exception e) {
                System.out.println("没有对应的方法：" + e);
            }
        }
        return bean;
    }
}
